const User = require('../models/user.model');
const jwt = require('jsonwebtoken');

exports.updateProfile = async (req, res) => {
  try {
    const { username, email } = req.body;
    const user = await User.findById(req.user._id);

    // 检查邮箱是否被其他用户使用
    if (email !== user.email) {
      const existingUser = await User.findOne({ email });
      if (existingUser) {
        return res.status(400).json({ error: '该邮箱已被使用' });
      }
    }

    // 检查用户名是否被其他用户使用
    if (username !== user.username) {
      const existingUser = await User.findOne({ username });
      if (existingUser) {
        return res.status(400).json({ error: '该用户名已被使用' });
      }
    }

    user.username = username;
    user.email = email;
    await user.save();

    res.json({
      id: user._id,
      username: user.username,
      email: user.email,
      role: user.role
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

exports.updatePassword = async (req, res) => {
  try {
    const { currentPassword, newPassword } = req.body;
    const user = await User.findById(req.user._id);

    const isMatch = await user.comparePassword(currentPassword);
    if (!isMatch) {
      return res.status(400).json({ error: '当前密码错误' });
    }

    user.password = newPassword;
    await user.save();

    res.json({ message: '密码更新成功' });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
}; 